package com.ac.service;

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ac.exception.RRException;
import com.ac.model.LogSystem;
import com.ac.model.Page;
import com.ac.model.query.LogSystemQ;
import com.ac.response.HttpStatus;
import com.ac.util.MongoUtil;
import com.ac.util.StrUtils;

import lombok.AllArgsConstructor;

@Service
@AllArgsConstructor
public class LogSystemService {

	final MongoTemplate mongo;

	public Page list(LogSystemQ uq) {
		Criteria ct = new Criteria();
		String type = uq.getType();
		String ip = uq.getIp();
		String title = uq.getTitle();
		int code = uq.getCode();
		String content = uq.getContent();

		if (!StrUtils.isEmpty(type)) {
			ct.and("type").is(type);
		}
		if (code != 0) {
			ct.and("code").is(code);
		}
		if (!StrUtils.isEmpty(ip)) {
			ct.and("ip").regex(ip);
		}
		if (!StrUtils.isEmpty(title)) {
			ct.and("title").regex(title);
		}
		if (!StrUtils.isEmpty(content)) {
			ct.and("content").regex(content);
		}

		return MongoUtil.findPge(uq, LogSystem.class, ct, Sort.by(Sort.Order.desc("createTime")));
	}

	@Transactional(rollbackFor = Exception.class)
	public void insert(LogSystem api) {
		api.insert();
		mongo.insert(api);
	}

	@Transactional(rollbackFor = Exception.class)
	public void removeAll(LogSystem obj) {
		String type = obj.getType();
		String content = obj.getContent();
		Criteria ct = new Criteria();
		if (type.equals("type")) {
			ct.and("type").is(content);
		} else if (type.equals("code")) {
			ct.and("code").is(Integer.parseInt(content));
		} else if (type.equals("all")) {
		} else {
			throw new RRException("操作异常", HttpStatus.BUG);
		}
		mongo.findAllAndRemove(Query.query(ct), LogSystem.class);
	}

}
